import React from 'react';
import { Form, Input, Select, message, Button, Icon } from 'antd';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import { API_HOST } from 'Constants/config';
import VR_TYPE from 'Constants/vrType';
import PicturesWall from '../../../../../UploadImage';
import EqualBorder from './../../../../../CommonComponents/EqualBorder';
import './index.scss';

const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
class AddPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isAdd: false,
      id: props.params.id,
      editRecord: '',
      viewRecord: [],
      isLoading: false,
      mediaType: ''
    };
    this.onEnter = ::this.onEnter;
    this.initForm = ::this.initForm;
    this.initList = ::this.initList;
  }
  componentDidMount() {
    this.initForm();
    this.initList();
    const { id } = this.state;
    if (!id) {
      document.getElementById('close').style.display = 'none';
    }
  }
  componentWillMount() {
    const { id } = this.state;
    if (!id) {
      this.setState({ isAdd: true },
      );
    }
  }
  initList() {
    const api = new Api({
      method: 'GET',
      path: '/directorys',
      success: (json) => {
        this.setState({ viewRecord: json });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initForm() {
    const { id } = this.state;
    if (id) {
      const api = new Api({
        method: 'GET',
        path: `/processes/${id}`,
        success: (json) => {
          this.setState({ editRecord: json, mediaType: json.media_type });
          if (!json.flow_vr) {
            document.getElementById('close').style.display = 'none';
          }
          if (json.flow_vr) {
            this.insertVrInfos(json.media_type, json.flow_vr);
          }
        },
        error: (msg) => {
          message.error(msg);
        }
      });
      api.run();
    }
  }
  returnVrType(type) {
    if (type.indexOf('video') > -1) {
      return VR_TYPE.video;
    }
    if (type.indexOf('image') > -1) {
      return VR_TYPE.img;
    }
    return false;
  }
  insertVrInfos(mediaType, media) {
    if (this.returnVrType(mediaType) === VR_TYPE.video) {
      if (!this.vrVideo) {
        this.vrVideo = new VRView.Player('#video', {
          width: '100%',
          height: '300',
          video: `${API_HOST}/files/${media}`,
          is_stereo: false,  //区分是mono还是stereo
        });
      } else {
        this.vrVideo.setContent({
          video: `${API_HOST}/files/${media}`,
        });
      }
    }
    if (this.returnVrType(mediaType) === VR_TYPE.img) {
      if (!this.vrVideo) {
        this.vrVideo = new VRView.Player('#video', {
          width: '100%',
          height: '300',
          image: `${API_HOST}/files/${media}`,
          is_stereo: false,  //区分是mono还是stereo
        });
      } else {
        this.vrVideo.setContent({
          image: `${API_HOST}/files/${media}`,
        });
      }
    }
  }
  onEnter() {
    const self = this;
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const { id } = this.state;
        const formValue = this.props.form.getFieldsValue();
        const currentValue = this.state.editRecord || {};
        let newRecord = { ...currentValue, ...formValue, releaser: '张三' };
        newRecord.flow_vr = this.state.type;
        self.setState({ isLoading: true });
        console.log(newRecord);
        if (id) {
          console.log(id);
          const editApi = new Api({
            method: 'PATCH',
            path: `/processes/admin/${id}`,
            data: {
              ...newRecord,
              media_type: this.state.mediaType
            },
            success: () => {
              this.setState({ isLoading: false });
              this.props.dispatch(routerActions.goBack());
            },
            error: (msg) => {
              message.error(msg);
              this.setState({ isLoading: false });
            }
          });
          editApi.run();
        } else {
          const addApi = new Api({
            method: 'POST',
            path: '/processes/admin',
            data: {
              ...newRecord,
              media_type: this.state.mediaType
            },
            success: (json) => {
              newRecord = json;
              this.setState({ isLoading: false });
              this.props.dispatch(routerActions.goBack());
            },
            error: (msg) => {
              message.error(msg);
              this.setState({ isLoading: false });
            }
          });
          addApi.run();
        }
      }
    });
  }
  uploadVideo() {
    const file = document.getElementById('upload').files[0];
    const formData = new window.FormData();
    formData.append('upload_file', file, file.name);
    const api = new Api({
      method: 'POST',
      path: '/files',
      noHeader: true,
      data: formData,
      success: (json) => {
        document.getElementById('close').style.display = 'block';
        this.setState({
          type: json.id,
          src: `${API_HOST}/files/${json.id}`,
          mediaType: this.returnVrType(file.type)
        });
        this.insertVrInfos(file.type, json.id);
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  handleDeleteVr() {
    this.props.form.setFieldsValue({ flow_vr: undefined });
    document.getElementById('video').innerHTML = '';
    this.setState({
      mediaType: '',
      type: ''
    });
    this.vrVideo = undefined;
    document.getElementById('close').style.display = 'none';
  }
  render() {
    const title = this.state.isAdd ? '新增' : '修改';
    const { form } = this.props;
    const initialValue = this.state.editRecord ? { ...this.state.editRecord } : '';
    const { getFieldDecorator } = form;
    return (
      <div className="run-once-add">
        <EqualBorder
          title={`最多跑一次${title}`}
          content={
            <div className="run-once-content-wrap">
              <Form layout={'horizontal'} className="report-form" >
                <FormItem label="类别" >
                  {getFieldDecorator('parent_id', {
                    initialValue: initialValue ? `${initialValue.parent_id}` : undefined,
                    rules: [
                      { required: true, message: '请选择类别' }
                    ]
                  })(
                    <Select placeholder="请选择" className="sel-input" style={{ width: 840 }}>
                      {
                        this.state.viewRecord.map((item) => {
                          return (<Option key={item.id} >{item.name}</Option >);
                        })
                      }
                    </Select >
                  )}
                </FormItem >
                <FormItem label="办事流程说明" >
                  {getFieldDecorator('process_name', {
                    initialValue: initialValue ? `${initialValue.process_name}` : '',
                    rules: [
                      { required: true, message: '请输入流程说明' }
                    ]
                  })(
                    <Input placeholder="请输入流程说明" style={{ width: 840 }} />
                  )}
                </FormItem >
                <FormItem label="LOGO" >

                  {getFieldDecorator('logo', {
                    initialValue: initialValue ? `${initialValue.logo}` : '',
                    rules: [
                      { required: true, message: '请选择logo' }
                    ]
                  })(
                    <PicturesWall
                      initImg={initialValue.logo ? [initialValue.logo] : []}
                      isOpen={initialValue.logo !== undefined}
                    />
                  )}
                </FormItem >
                <FormItem label="简介" >
                  {getFieldDecorator('introduction', {
                    initialValue: initialValue ? `${initialValue.introduction}` : '',
                    rules: [
                      { required: true, message: '请输入简介' }
                    ]
                  })(
                    <TextArea placeholder="请输入简介" rows={4} style={{ height: 300, width: 840 }} />
                  )}
                </FormItem >
                <FormItem label="图片" >
                  {getFieldDecorator('flow_chat', {
                    initialValue: initialValue ? `${initialValue.flow_chat}` : '',
                    rules: [
                      { required: true, message: '请选择图片' }
                    ]
                  })(
                    <PicturesWall
                      initImg={initialValue.flow_chat ? [initialValue.flow_chat] : []}
                      isOpen={initialValue.flow_chat !== undefined}
                    />
                  )}
                </FormItem >
                <FormItem label="VR" >

                  {getFieldDecorator('flow_vr', {
                  })(
                    <div style={{ width: 840, textAlign: 'left' }} className="opreate-vr-wrap">
                      <input type="file" accept="video/*,image/*" id="upload" onChange={this.uploadVideo.bind(this)} />
                      <img src="images/dispatch/icon_add.png" alt="添加" />
                      <div id="video" >{''}</div>
                      <Icon id="close" type="close-circle-o" className="vr-close" onClick={this.handleDeleteVr.bind(this)} />
                    </div>
                  )}
                </FormItem >
              </Form >
              <div className="b-wrap">
                <Button
                  className="ok-btn"
                  onClick={this.onEnter.bind(this)}
                  loading={this.state.isLoading}
                >
                  <img src="images/dispatch/icon_public.png" alt="发布" />
                  发布
                </Button >
              </div>
            </div>
          }
        />
      </div>
    );
  }
}


function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default Form.create()(connect(mapStateToProps)(AddPage));
